package com.airnewslinkosky.ticket.util;

import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.airnewslinkosky.ticket.net.AndroidHttpClient;



public class FileUtils {  
	/**  
     * LogCat TAG 标识  
     */  
    public static final String TAG = "FileUtils";   
   
    
    /**
     * 解压zip格式文件
     * @param urlPath
     * @param context
     * @return
     */
    public static HashMap<String, File> Decompresses(String urlPath, Context context){
		File myTempFilePath = new File(Environment.getExternalStorageDirectory(),null);// Constants.DOWNLOAD_DIR
		if(!myTempFilePath.exists()){
			myTempFilePath.mkdir();
		}
		
    	HashMap<String, File> fileMap = new HashMap<String, File>();
    	AndroidHttpClient client = null;
		//client = AndroidHttpClient.newInstance(context, Constants.USER_AGENT);
		HttpGet request = new HttpGet(urlPath);
		ZipInputStream in = null;
		FileOutputStream out = null;
        try {
        	HttpResponse response = client.execute(request);
            
            int statusCode = response.getStatusLine().getStatusCode();
            InputStream is = null;
            if (statusCode == HttpStatus.SC_OK){        	
            	is = response.getEntity().getContent();
        		in = new ZipInputStream(is);
        		ZipEntry entry;
        		byte[] buf = new byte[1024];
        		int len;
        		while ((entry = in.getNextEntry()) != null) {
        			String zipName = entry.getName();
        			if (zipName.endsWith("/")) {
        				new File(zipName).mkdirs();
        				continue;
        			}
        			/* 创建临时文件 */
        			File myTempFile = new File(myTempFilePath, zipName);
        			out = new FileOutputStream(myTempFile);
        			while ((len = in.read(buf)) > 0) {
        				out.write(buf, 0, len);
        			}
        			out.close();
        			Log.d(TAG, myTempFile.getAbsolutePath());
        			fileMap.put(zipName, myTempFile);
        		}
            }
        } catch (Exception ex) {
            request.abort();
            ex.printStackTrace();
        }finally{
        	closeStream(in);
        	closeStream(out);
    		if (client != null) {
                client.close();
                client = null;
            }	
        }
		return fileMap;
	}


	private static void closeStream(Closeable closeable)  {
		if(closeable != null){
			try {
				closeable.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
       
}
